#!/usr/bin/perl -w
# 
# Task C (3 points)
# Write a program that creates a 2-dimensional array consisting of 
# three array references. Each referenced array should contain three 
# numbers. The program should then iterate over all elements in the 
# 2-dimensional array and count how many numbers that are negative. 
# The number of negative numbers should then be given as output.
#
#
#
#
use warnings;
use strict;
#
#
sub matrix_element;
#
# Create and fill the 2 x 2 matrix
my $M = 2;
my $N = 2;
#
my @matrix;
#
my $i, my $j;
for ($i = 0; $i<$M; $i++){
    for ($j = 0; $j<$N; $j++){
        # Each matrix element is a reference to three array references
        $matrix[$i][$j] = matrix_element();
    }	
}
# 
# Next, we retrieve each negative number and count it
my $count = 0;
for ($i = 0; $i<$M; $i++){
    for ($j = 0; $j<$N; $j++){
        # Each matrix element is a reference to three array references
        my @three = @{$matrix[$i][$j]}; 
        # 'three' is a 3 x 3 matrix
        my $ii,my $jj;
        for ($ii = 0; $ii<3; $ii++){
            for ($jj = 0; $jj<3; $jj++){
                if ($three[$ii][$jj]<0) {$count++;}
            }
        }   
    }
}
#
print ("The number of negative numbers is: $count");

sub matrix_element{
	# The subroutine returns a reference to an array of three referenced arrays
	 # of three numbers
	my $i;
	my $j;
	my @m;
	# m is a 3-long array of references to 3-arrays
	for ($i = 0; $i<3; $i++){
      for ($j = 0; $j<3; $j++){
      	# fill the matrix with a random number between -10 and +10
	   $m[$i][$j] = int(rand(20))-10;
	   }
	}
    my @three_array_references = (\@{$m[0]}, \@{$m[1]},\@{$m[2]} );
    return \@three_array_references; 	
}